const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db, Op, QueryTypes} = require("../../models/db");
router.post('/app/getGoodList', async ctx => {
    let tenantId= ctx.user.tenantId
    let uid= ctx.user.id
    let body= ctx.request.body

    let keyWord= body.keyWord?body.keyWord:''
    let goodCatId= body.goodCatId?body.goodCatId:''
    let buId= body.buId?body.buId:''
    let currentPage= body.currentPage
    let pageSize= body.pageSize?body.pageSize:30
    let offset = (currentPage - 1) * pageSize;
    let list = []
    let total = 0
    if(keyWord) {
        let sql = `select id,name,spec,unit1,unit2 from v_goods where tenantId=${tenantId} `
        if(keyWord) {
            sql += ` and(name like '%${keyWord}%' or pinYin like '%${keyWord}%' or barCode  like '%${keyWord}%' or barCode1  like '%${keyWord}%') `
        }
        total = await db.query(`select count(*) total from (${sql}) a `,{type: QueryTypes.SELECT, plain: true})
        list = await db.query(`select * from (${sql}) a order by id desc offset ${offset} rows fetch  next ${pageSize} rows only ;`,{type: QueryTypes})
    }
    else {
        if(goodCatId) {
            if(goodCatId === 'near') {
                let sql = ` select distinct b.id,b.name,b.spec,b.unit1,b.unit2 from (
                select * from contact_goods where tenantId=${tenantId} and transType=150601 and buId=${buId}) a inner join v_goods b on a.tenantId=b.tenantId and a.invId=b.id  `
                if(keyWord) {
                    sql += ` and(b.name like '%${keyWord}%' or b.pinYin like '%${keyWord}%' or b.barCode  like '%${keyWord}%' or b.barCode1  like '%${keyWord}%') `
                }
                total = await db.query(`select count(*) total from (${sql}) a `,{type: QueryTypes.SELECT, plain: true})
                list = await db.query(`select * from (${sql}) a order by id desc offset ${offset} rows fetch  next ${pageSize} rows only ;`,{type: QueryTypes})
            }
            else {
                let sql = `select id,name,spec,unit1,unit2 from v_goods where tenantId=${tenantId} and categoryId=${goodCatId} `
                if(keyWord) {
                    sql += ` and(name like '%${keyWord}%' or pinYin like '%${keyWord}%' or barCode  like '%${keyWord}%' or barCode1  like '%${keyWord}%') `
                }
                total = await db.query(`select count(*) total from (${sql}) a `,{type: QueryTypes.SELECT, plain: true})
                list = await db.query(`select * from (${sql}) a order by id desc offset ${offset} rows fetch  next ${pageSize} rows only ;`,{type: QueryTypes})
            }
        }
        else {
            let sql = `select id,name,spec,unit1,unit2 from v_goods where tenantId=${tenantId} `
            total = await db.query(`select count(*) total from (${sql}) a `,{type: QueryTypes.SELECT, plain: true})
            list = await db.query(`select * from (${sql}) a order by id desc offset ${offset} rows fetch  next ${pageSize} rows only ;`,{type: QueryTypes})
        }
    }
    let ids = []
    list.map(row => {
        ids.push(row.id)
    })

    if(ids.length > 0) {
        let  sql = ` select max(id) id,buId,invId,price,deduction,unit from v_price_his_last where tenantId=${tenantId} 
         and transType=150601 and buId=${buId} and invId in(${ids.join(',')}) and isnull(price,0)>0  GROUP BY buId,invId,price,deduction,unit `
        let ret = await db.query(sql, {type: QueryTypes.SELECT})
        list.map(row => {
            ret.map(g => {
                if(row.id===g.invId && row.unit1===g.unit) {
                    row.price = tool.xe.toFixed(g.price, 2)
                }
            })
        })
    }
    // 赠品
    if(ids.length > 0) {
        let send = `SELECT a.tenantId,a.buId,a.invId,a.sendInvId,a.buyQty,a.sendQty,b.name sendInvName from send a 
                        inner join v_goods b on a.tenantId=b.tenantId and a.sendInvId=b.id
                        WHERE a.id in (SELECT max(id) id from send a  WHERE a.tenantId=${tenantId} and a.buId=${buId} and a.invId in(${ids.join(',')})) `
        let sendList = await db.query(send, {type: QueryTypes.SELECT})
        list.map(row => {
            sendList.map(g => {
                if(row.id===g.invId) {
                    row.send = ` 买${g.buyQty}赠${g.sendQty} `
                }
            })
        })
    }
    // 库存
    if(ids.length > 0) {
        let sqls = `with bills as (select invId, sum(isnull(lastCount, 0)) lastCount
                                   from inventory
                                   where tenantId = ${tenantId}
                                     and invId in (${ids.join(',')})
                                   group by invId
        ) select a.invId,dbo.setAssQty(a.lastCount,b.spec,b.unit1,b.unit2) leftQty from bills a inner join v_goods b on a.invId=b.id                
        `
        let kc = await db.query(sqls, {type: QueryTypes.SELECT})
        list.map(row => {
            kc.map(g => {
                if(row.id===g.invId) {
                    row.leftQty = g.leftQty
                }
            })
        })
    }
    return ctx.suc('', {
        total: total.total,
        list
    })

})


module.exports = router;